<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/8/18
 * Time: 11:15
 */

namespace app\logic\cron;


use app\common\lib\Common;
use app\common\lib\Constant;
use app\common\lib\RedisQueue;
use app\common\lib\TencentCos;
use app\exception\IndexException;
use app\logic\BaseLogic;

use app\model\material\MaterialDataModel;
use app\model\redis\RedisQueueModel;
use app\model\user\UserIncomeFlowModel;
use app\model\user\UserInviteRelationModel;
use app\model\user\UserModel;
use app\model\user\UserPointFlowModel;
use app\model\user\UserPromotionOrderIncomeModel;
use app\model\user\UserPromotionPlanModel;
use app\model\user\UserRechargeOrderIncomeModel;
use app\model\user\UserRechargeOrderModel;
use app\model\vip\ReceiveVipByMobileModel;
use support\Db;

class MaterialLogic extends BaseLogic
{
    protected static $instance;

    public function __construct()
    {
        parent::__construct();
    }

    public static function getInstance()
    {
//        if (is_object(self::$instance)) {
//            return self::$instance;
//        }

        return  new self();
    }

    public function sysncMaterial()
    {
        $queueKey = '{redis-queue}-waitingasyncVideoMaterial';
        $redisQueues = \Webman\RedisQueue\Redis::connection()->lRange($queueKey,0,-1);
        $ids = [];
        foreach($redisQueues as $q){
            $qData = json_decode($q, true);
            $ids[] = $qData['data']['materialid'];
        }

        $where = ['isdel'=>0];
        if(!empty($ids)){
            $where[] = ['id','in',$ids];
        }
        $data = MaterialDataModel::getInstance()->getWhere($where)->orderBy('created_at','asc')->get();
        foreach ($data as $material){
            $isChange = false;
            if($material['heigh_material_path']){
                $heightVideoData = $material['orig_heigh_video_data'] ? json_decode($material['orig_heigh_video_data'], true) : [];
                $heightVideos = array_column($heightVideoData,'video');
                $videos = $this->sysncMaterialVideoByPath($material['heigh_material_path']);
                if (!empty($videos)) {
                    foreach($videos as $video){
                        if(!in_array($video['video'],$heightVideos)){
                            $isChange = true;
                        }
                    }
                    $material->orig_heigh_video_data = $videos;
                }
            }

            if($material['normal_material_path']){
                $normalVideoData = $material['orig_normal_video_data'] ? json_decode($material['orig_normal_video_data'], true) : [];
                $normalVideos = array_column($normalVideoData,'video');
                $videos = $this->sysncMaterialVideoByPath($material['normal_material_path']);
                if (!empty($videos)) {
                    foreach($videos as $video){
                        if(!in_array($video['video'],$normalVideos)){
                            $isChange = true;
                        }
                    }
                    $material->orig_normal_video_data = $videos;
                }
            }

            $material->save();
            if($isChange){
                //生成唯一的请求id
                $requestId = Common::getRequestId();

                // 队列名
                $queue = 'asyncVideoMaterial';
                // 数据，可以直接传数组，无需序列化
                $data = ['requestid' => $requestId, 'materialid' => $material['id']];
                // 投递消息
                RedisQueue::getInstance()->sendQueue($queue, $data);
            }

            sleep(1);
        }

        return ['success'];
    }

    public function sysncMaterialVideoByPath($pathData)
    {
        if($pathData==false){
            return [];
        }

        $paths = explode(',',$pathData);
        $videos = [];
        $urls = [];
        foreach($paths as $path){
            $marker = '';
            while (true){
                $result = TencentCos::getInstance()->getBucketListObject($path,$marker);

                if(!empty($result['Contents'])){
                    if(!empty($result['NextMarker']) && (urldecode($result['NextMarker'])==$marker)){
                        break;
                    }

                    foreach ($result['Contents'] as $res){
                        if($res['Size']>0){
                            $url = 'https://'.$result['Location'].$res['Key'];
                            $arr = explode('/',$url);
                            $name = $arr[count($arr)-1];
                            !in_array($url,$urls) && $videos[] = ['video'=>$url,'name'=>substr($name,-14)];
                            !in_array($url,$urls) && $urls[] = $url;
                        }
                    }
                    if(!empty($result['NextMarker']) && (urldecode($result['NextMarker'])!=$marker)){
                        $marker = urldecode($result['NextMarker']);
                    }else{
                        break;
                    }
                }else{
                    break;
                }
            }
        }

        return $videos;
    }

}